package com.pan.insist.util;

import lombok.extern.log4j.Log4j2;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

/**
 * 工具类 - Spring
 *
 * @author kaiji
 */
@Log4j2
@Component
public class SpringUtil implements ApplicationContextAware {

	private static ApplicationContext applicationContext;

	@Override
	public void setApplicationContext(ApplicationContext applicationContext)
			throws BeansException {
		if (SpringUtil.applicationContext == null) {
			log.info("SpringUtil.applicationContext is null. SpringUtil is now being created");
			SpringUtil.applicationContext = applicationContext;
		}
	}

	/**
	 * 获取applicationContext 貌似没有用到 所以先注释掉
	 */
	public static ApplicationContext getApplicationContext() {
		return applicationContext;
	}

	/**
	 * 根据Bean名称获取实例
	 * 
	 * @param name
	 *            Bean注册名称
	 * @throws BeansException
	 * 		异常信息对象
	 * @return bean实例
	 */
	public static Object getBean(String name) throws BeansException {
		return getApplicationContext().getBean(name);
	}

	/**
	 * 通过class获取Bean.
	 * @param clazz
	 * 		类
	 * @param <T>
	 *     	泛型
	 * @return 类的实例
	 */
	public static <T> T getBean(Class<T> clazz){
		return getApplicationContext().getBean(clazz);
	}

	/**
	 * 通过name,以及Clazz返回指定的Bean
	 * @param name
	 * 		类型名称
	 * @param clazz
	 * 		类
	 * @param <T>
	 *     	泛型
	 * @return 类的实例
	 */
	public static <T> T getBean(String name, Class<T> clazz){
		return getApplicationContext().getBean(name, clazz);
	}
}